package com.qb.devstore;

import androidx.constraintlayout.widget.ConstraintLayout;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xuexiang.xui.XUI;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import utils.AppUtil;
import utils.DownloadUtil;
import utils.MyUtil;

public class TaskActivity extends Activity {
    Context ctx;
    ConstraintLayout clProgress;
    ProgressBar pbDown;
    TextView tvProgress,tvError,tvDone;
    Button btnDownStop,btnDownReset,btnDownClose;
    DownloadUtil dlu;
    Boolean isCancel = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        XUI.initTheme(this);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_task);
        ctx = this;
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        StatusBarUtils.initStatusBarStyle(this, false, 0x00000000);

        String apkName = getIntent().getStringExtra("apkName");
        String apkVersion = getIntent().getStringExtra("apkVersion");
        String apkMem = getIntent().getStringExtra("apkMem");
        String apkIcon = getIntent().getStringExtra("apkIcon");
        String apkUrl = getIntent().getStringExtra("apkUrl");
        String apkSize = getIntent().getStringExtra("apkSize");

        TextView tvName = findViewById(R.id.tv_down_label);
        TextView tvVer = findViewById(R.id.tv_down_version);
        TextView tvMem = findViewById(R.id.tv_down_mem);
        tvName.setText(apkName);
        tvVer.setText(apkVersion);
        tvMem.setText(apkSize+apkMem);

        ImageView ivIcon = findViewById(R.id.iv_down_icon);
        try {
            requestImg(ivIcon,new URL(apkIcon));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        clProgress = findViewById(R.id.cl_down_progress);
        tvError = findViewById(R.id.tv_down_error);
        tvDone = findViewById(R.id.tv_down_done);
        pbDown = findViewById(R.id.pb_down);
        tvProgress = findViewById(R.id.tv_down_progress);

        btnDownClose = findViewById(R.id.btn_down_close);
        btnDownClose.setOnClickListener(view -> {
            showCustomDialog();
        });
        btnDownStop = findViewById(R.id.btn_down_stop);
        btnDownStop.setOnClickListener(view -> {
            showCustomDialog();
        });
        btnDownReset = findViewById(R.id.btn_down_reset);
        btnDownReset.setOnClickListener(view -> {
            dloadApk(this,apkUrl,apkName,false);
        });
        dloadApk(this,apkUrl,apkName,false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyUtil.showLog("taskactivity","onDestroy");
    }

    @Override
    public void onBackPressed() {
        showCustomDialog();
    }

    private int progressCount = 0;
    private Boolean downloadDone = false;
    private void dloadApk(Context ctx, String urlStr, String name, Boolean silence) {
        String apkName = name + urlStr.substring(urlStr.lastIndexOf("."));
        String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download/";
        if(MyUtil.isFolderExists(destFileDir)) {
            String apkPath = destFileDir+apkName;
            MyUtil.showLog("dloadApk","开始下载");
            dlu = new DownloadUtil(urlStr);
            progressCount = 0;
            downloadDone = false;
            tvError.setVisibility(View.GONE);
            tvDone.setVisibility(View.GONE);
            clProgress.setVisibility(View.VISIBLE);
            btnDownStop.setVisibility(View.VISIBLE);
            btnDownReset.setVisibility(View.GONE);
            btnDownClose.setVisibility(View.GONE);
            dlu.download(destFileDir, apkName, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(File file) {
                    MyUtil.showLog("dloadApk","下载完成progressCount="+progressCount);
                    downloadDone = true;
                    if (progressCount > 100) {
                        //下载完成进行相关逻辑操作
                        showDloadMsg("success");
                        if (silence) {
                            // 静默安装
                        } else {
                            runOnUiThread  (()->{
                                new Handler().postDelayed(()-> {
                                    Boolean installSuccess = AppUtil.installApk(ctx,apkPath);
                                    if (installSuccess) {
                                        MyUtil.showLog("dloadApk","installSuccess");
                                    } else {
                                        showDloadMsg("下载失败，不是有效的安装程序");
                                    }
                                },1000);
                            });
                        }
                    } else {
                        showDloadMsg("下载失败，不是有效的安装程序");
                    }
                }
                @Override
                public void onDownloading(int progress) {
                    //下载进行中展示进度
//                    MyUtil.showLog("dloadApk","下载进度:"+progress);
                    progressCount = progressCount + progress;
                    if (silence) {
                        // 系统更新不显示进度
                    } else {
                        //setNotification(ctx,nId,progress,apkName,dlu);
                        runOnUiThread(() -> {
                            pbDown.setProgress(progress);
                            tvProgress.setText(progress+"%");
                        });
                    }
                }

                @Override
                public void onDownloadFailed(Exception e) {
                    //下载异常进行相关提示操作
                    MyUtil.showLog("dloadApk",apkName+"下载失败"+e);
                    showDloadMsg(isCancel?"取消下载":"下载失败"+e.getMessage());
                }
            });
        } else {
            MyUtil.showLog("dloadApk",apkName+"下载失败"+"目录不存在");
            showDloadMsg("创建下载文件失败");
        }
    }

    private void showDloadMsg(String msg) {
        runOnUiThread(() -> {
            if (msg.equals("success")) {
                tvError.setVisibility(View.GONE);
                tvDone.setVisibility(View.VISIBLE);
                clProgress.setVisibility(View.GONE);
                btnDownStop.setVisibility(View.GONE);
                btnDownReset.setVisibility(View.GONE);
                btnDownClose.setVisibility(View.VISIBLE);
            } else {
                tvError.setText(msg);
                tvError.setVisibility(View.VISIBLE);
                clProgress.setVisibility(View.GONE);
                btnDownStop.setVisibility(View.GONE);
                btnDownReset.setVisibility(View.VISIBLE);
                btnDownClose.setVisibility(View.VISIBLE);
            }
        });
    }

    private void showCustomDialog() {
        if (downloadDone) {
            finish();
            return;
        }
        MaterialDialog.Builder md = new MaterialDialog.Builder(ctx);
        md.title("取消下载");
        md.icon(ctx.getResources().getDrawable(R.drawable.ic_baseline_error_outline_32));
        md.content("是否确认取消下载");
        md.positiveText("确定");
        md.onPositive((dialog, which) -> {
            isCancel = true;
            dlu.call.cancel();
            finish();
        });
        md.negativeText("关闭");
        md.negativeColorRes(R.color.gray);
        md.show();
    }

    private void requestImg(ImageView iv, final URL imgUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = BitmapFactory.decodeStream(imgUrl.openStream());
                    showImg(iv,bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showImg(ImageView iv, final Bitmap bitmap){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                iv.setImageBitmap(bitmap);
            }
        });
    }
}